package com.aimao.blog.service.impl;

import com.aimao.blog.config.CustomUploadConfig;
import com.aimao.blog.dao.ImageMapper;
import com.aimao.blog.util.CustomMap;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.io.File;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @Author PuaChen
 * @Create 2018-08-02 16:24
 */
@Service
public class AutoClearOverdueImg {

    @Autowired
    private ImageMapper imageMapper;

    @Autowired
    private CustomUploadConfig customUploadConfig;

    private Logger log = LoggerFactory.getLogger(getClass());

    /**
     * 计算总共有多少图片
     *
     * @return
     */
    public int getImgFileSize() {
        int size = 0;
        size = imageMapper.selectImgAllByAdmin().size() +
                imageMapper.selectImgAllByArticle().size() +
                imageMapper.selectImgAllBySubject().size() +
                imageMapper.selectBannerImages().size();

        for (String content : imageMapper.selectArticleContent()) {
            Elements items = Jsoup.parse(content).select("img");
            if (items != null) {
                size += items.size();
            }
        }
        return size;
    }

    /**
     * 返回文件中有用的图片数量
     *
     * @return
     */
    public int getImgFileSizeByDir() {
        File root = new File(customUploadConfig.getDirFilePath());
        return root.listFiles(pathname -> {
            String name = pathname.getName();
            if (name.endsWith(".png")
                    || name.endsWith(".jpg")
                    || name.endsWith(".gif")
                    || name.endsWith(".jpeg")
                    || name.endsWith(".ico")) {
                return true;
            }
            return false;
        }).length;
    }


    /**
     * 自动删除 用不到的文件
     *
     * @return
     */
    public boolean autoDelete() {
        boolean isSuccess = true;
        try {
            //第一步删除主图的文件
            Set<String> set = new HashSet<>();
            set.addAll(imageMapper.selectImgAllByAdmin());
            set.addAll(imageMapper.selectImgAllByArticle());
            set.addAll(imageMapper.selectImgAllBySubject());
            set.addAll(imageMapper.selectBannerImages());

            Set<String> data = set.stream()
                    .map(s -> s.substring(s.lastIndexOf("/") + 1))
                    .collect(Collectors.toSet());

            //读取文章内容里面的图片信息
            //清空初始化容器
            set.clear();
            for (String content : imageMapper.selectArticleContent()) {
                Elements items = Jsoup.parse(content).select("img");
                if (items != null && !items.isEmpty()) {
                    for (Element img : items) {
                        set.add(img.attr("src"));
                    }
                }
            }
            //容器已经填满了 进行筛选操作
            set = set.stream()
                    .map(s -> s.substring(s.lastIndexOf("/") + 1))
                    .collect(Collectors.toSet());

            set.addAll(data);
            //删除的操作进行
            deleteFile(set);

        } catch (Exception e) {
            log.error("删除无用图片出现错误：", e);
            isSuccess = false;
        }
        if (isSuccess) {
            log.info("删除无用图片成功!");
        }
        return isSuccess;
    }


    private void deleteFile(Set<String> data) throws Exception {
        File root = new File(customUploadConfig.getDirFilePath());

        File[] files = root.listFiles(pathname -> {
            String name = pathname.getName();
            if (name.endsWith(".png")
                    || name.endsWith(".jpg")
                    || name.endsWith(".gif")
                    || name.endsWith(".jpeg")
                    || name.endsWith(".ico")) {
                return true;
            }
            return false;
        });

        //需要删除的文集集合
        Set<File> delList = new HashSet<>();

        for (File file : files) {
            boolean isDel = true;
            for (String datum : data) {
                if (file.getName().equals(datum)) {
                    isDel = false;
                }
            }
            if (isDel) {
                delList.add(file);
            }
        }
        //需要删除的文件
        for (File file : delList) {
            file.delete();
        }
    }


    /**
     * 返回系统设置状态
     *
     * @return
     */
    public Map<String, Object> getDirConfig() {
        return CustomMap.create().add("url", customUploadConfig.getUrl())
                .add("dir", customUploadConfig.getDirFilePath());
    }

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 清空数据库的所有数据
     */
    public void clearChache() {
        redisTemplate.execute((RedisCallback) connection -> {
            connection.flushDb();
            return null;
        });
    }

}
